<template>
  <section>
    <!--查询-->
    <div class="search">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="年级">
          <el-select value-key="id" filterable clearable size="small" v-model="queryParams.gradeNo" placeholder="请选择"
            @change="handleChangeGrade">
            <el-option v-for="item in gradeOptions" :key="item.id" :label="item.name" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select filterable clearable size="small" v-model="queryParams.classNo" placeholder="请选择">
            <el-option v-for="item in classOptions" :key="item.classNo" :label="item.name" :value="item.classNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input clearable size="small" v-model.trim="queryParams.name"></el-input>
        </el-form-item>
        <el-form-item label="测量时间">
          <el-date-picker v-model="measureTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="small" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-checkbox v-model="queryParams.abnormal"></el-checkbox>
          <span style="margin-left: 10px">温度≥37.3℃</span>
        </el-form-item>
        <el-form-item>
          <el-button v-if="checkAuthority('/select')" size="small" type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="mb-10" style="display: flex; justify-content: end;">
        <div v-if="checkAuthority('/stu/eyes')" class="switch-btn cursor iconfont" :class="[isShow ? 'icon-yanjing': 'icon-biyan']"
          @click="handleClickIsShow"></div>
        <div>
          <el-button v-if="checkAuthority('/teacher/import')" size="small" type="primary" @click="handleBrachAdd">导入</el-button>
          <el-button v-if="checkAuthority('/student/export')" size="small" type="primary" @click="handleExport">导出</el-button>
        </div>
      </div>
      <div></div>
    </div>
    <!--表格-->
    <acc-table :tableData="tableData" :columnDefs="columnDefs" @selection-change="handleSelectionChange">
      <template #selection />
      <template #order="{index}">
        <span>{{ index | orderIndex(pageVo) }}</span>
      </template>
      <template #idCard={row}>
        <div>{{isShow && row.idCard.length === 18 ? $options.filters.idCarDesensitization(row.idCard) : row.idCard}}
        </div>
      </template>
      <template #temperature="{row}">
        <template v-for="item in row.temperatureInfo || []">
          <div :key="item.temperature" class="titleaa" v-if="!abnormal || (abnormal && item.temperature >= 37.3)"
            :style="{ color: item.temperature >= 37.3 ? 'red' : '#606266' }">
            {{ item.temperature }}
          </div>
        </template>
      </template>
      <template #measureTime="{ row }">
        <template v-for="item in row.temperatureInfo || []">
          <div :key="item.measureTime" class="titleaa" v-if="!abnormal || (abnormal && item.temperature >= 37.3)">
            {{ item.measureTime }}
          </div>
        </template>
      </template>
      <template #action="{ row }">
        <el-button size="mini" type="text" @click="handleEdit(row)">编辑</el-button>
      </template>
    </acc-table>
    <acc-page :total="total" :page-size="pageVo.pageSize" :current-page="pageVo.pageNum"
      @current-change="handleChangePage" @size-change="handleChangeSize"></acc-page>
    <!--批量添加-->
    <el-dialog :visible.sync="visibleBrachAdd" width="400px" center>

      <div class="import-template" v-if="visibleBrachAdd">
        <div>
          <label>下载模板：</label>
          <el-link type="primary" @click="handleDownload">下载</el-link>
        </div>
        <div class="mb-20">
          <label>批量上传：</label>
          <el-upload style="display: inline" action="" :limit="1" :auto-upload="false" :show-file-list="true"
            accept=".xls,.xlsx,.zip" :before-upload="beforeUpload" :on-exceed="onExceed" :on-change="fileChange"
            :on-remove="handleRemove">
            <el-link type="primary">导入</el-link>
          </el-upload>
        </div>
        <div style="text-align: center">
          <el-button size="small" type="primary" @click="handleSave">确定</el-button>
          <el-button size="small" @click="handleCancelAdd">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--编辑-->
    <el-dialog :visible.sync="dialogEditVisible" width="640px">
      <template v-slot:title>
        <div class="dialog-title">
          <div class="dialog-btn cursor iconfont" :class="[isDialogShow ? 'icon-yanjing': 'icon-biyan']"
            @click="handleClickDialogIsShow"></div>
        </div>
      </template>
      <section>
        <!--详情-->
        <el-descriptions v-if="dialogEditVisible" class="detail-top" size="medium" :column="4">
          <el-descriptions-item label="姓名">{{
          details.name
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{
          details.gender
          }}</el-descriptions-item>
          <el-descriptions-item label="证件号码" :span="2">
            {{isDialogShow && details.idCard.length === 18 ? $options.filters.idCarDesensitization(details.idCard) :
            details.idCard}}
          </el-descriptions-item>
          <el-descriptions-item label="年级">{{
          details.gradeName
          }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{
          details.className
          }}</el-descriptions-item>
          <el-descriptions-item label="班内学号" :span="2">{{
          details.eduNo
          }}</el-descriptions-item>
        </el-descriptions>
        <!--表单-->
        <el-form :model="details" :inline="true" ref="ruleForm" class="detail-bottom">
          <div v-for="(item, index) in details.temperatureInfo" :key="`edit-${index}`">
            <div v-if="!abnormal || (abnormal && item.delTemperature >= 37.3)">
              <el-form-item label="体温" :prop="'temperatureInfo.' + index + '.temperature'"
                style="width: 50%; margin-right: 0" :rules="{
                  required: true,
                  message: '请输入体温',
                  trigger: 'blur',
                }">
                <el-input-number v-model="item.temperature" :precision="1" :step="0.1" :max="50" :min="0" size="mini">
                </el-input-number>
              </el-form-item>
              <el-form-item label="测量时间" style="width: 50%; margin-right: 0"
                :prop="'temperatureInfo.' + index + '.measureTime'" :rules="{
                  required: true,
                  message: '请选择测量时间',
                  trigger: 'change',
                }">
                <el-date-picker type="datetime" placeholder="选择日期" v-model="item.measureTime"
                  value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px" size="mini"></el-date-picker>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button size="small" @click="resetForm('ruleForm')">取消</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { decrypt, encrypt } from '@/utils/crypto'
import { columnDefs } from './mock'
import { getGradeList, getclassesList } from '@/views/children/antiepidemic/js/base'
import { getTemperatureStudentQuery, downloadTemplate, exportTemperatureStudent, importStudentTemperature, saveTemperatureStudent } from '@/views/children/antiepidemic/js/temperatureMonitoring'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
export default {
  data () {
    return {
      isShow: true,
      isDialogShow: true,
      queryParams: {
        classNo: null
      },
      gradeOptions: [],
      classOptions: [],
      columnDefs: [],
      tableData: [],
      pageVo: {
        pageNum: 1,
        pageSize: 10
      },
      abnormal: false,
      total: 0,
      tableSelectIds: [],
      file: '',
      visibleBrachAdd: false,
      dialogEditVisible: false,
      details: {},
      // ruleForm: {
      //   temperature: 36.0,
      //   measureTime: ''
      // },
      measureTime: [],
      rules: {
        temperature: [
          { required: true, message: '请输入体温', trigger: 'blur' }
        ],
        measureTime: [
          { required: true, message: '请选择测量时间', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.getGrade()
    this.onSubmit()
  },
  mounted () {
    this.columnDefs = columnDefs
  },
  methods: {
    checkAuthority,
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    handleClickDialogIsShow () {
      this.isDialogShow = !this.isDialogShow
    },
    // 获取年级接口
    getGrade () {
      getGradeList({ pageNum: 1, pageSize: 999, status: 1 }).then(res => {
        if (res.code !== 0) return
        this.gradeOptions = res.data.records
      })
    },
    // 年级变更事件函数
    handleChangeGrade (val) {
      this.queryParams.classNo = null
      this.classOptions = []
      if (val !== '') this.getclasses()
    },
    // 获取班级接口
    getclasses () {
      getclassesList({ gradeName: this.queryParams.gradeNo.name, status: 1, pageNum: 1, pageSize: 999 }).then(res => {
        if (res.code !== 0) return
        this.classOptions = res.data.classList.records
      })
    },
    // 查询函数
    onSubmit () {
      this.pageVo.pageNum = 1
      this.loadDataList()
    },
    // 校内体温检测 查询接口
    loadDataList () {
      let temp = {}
      Object.assign(temp, this.queryParams, this.pageVo)
      temp.beginTime = this.measureTime ? this.measureTime[0] : ''
      temp.endTime = this.measureTime ? this.measureTime[1] : ''
      temp.gradeNo = temp?.gradeNo?.no || null
      temp.userType = 0
      this.abnormal = temp.abnormal
      this.tableData = []
      getTemperatureStudentQuery(temp).then(res => {
        if (res.code !== 0) return
        res.data = JSON.parse(decrypt(res.data))
        this.total = res.data.total
        this.tableData = res.data.records
        console.log('t', this.tableData)
        // [{}].map((item) => {
        //   item.temperature = [{ value: '29', time: '2022-01-01' }, { value: '39', time: '2022-02-01' }]
        //   return item
        // })
      })
    },
    // 当前页改变监听函数
    handleChangePage (page) {
      this.pageVo.pageNum = page
      this.loadDataList()
    },
    handleChangeSize (size) {
      this.pageVo.pageSize = size
      this.onSubmit()
    },
    // 表格复选框
    handleSelectionChange (selection) {
      // 逻辑处理
      this.tableSelectIds = []
      this.tableSelectIds = selection.map(item => item.no)
    },
    // 下载模板
    async handleDownload () {
      try {
        let res = await downloadTemplate({ userType: 0 })
        if (res.code === 0) {
          this.$message.success('下载中')
        }
      } catch (e) { }
    },
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const zipType = file.name.split('.')[1] === 'zip'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2 && !zipType) {
        this.$message.warning('导入模板只能是xls、xlsx、zip格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('导入模板大小不能超过 200MB!')
        return false
      } else {
        this.loading = this.$loading({
          lock: true,
          text: '正在导入',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        })
        return true
      }
    },
    onExceed (files, fileList) {
      this.$message.warning(`只能选择一个文件`)
    },
    fileChange (file, fileList) {
      console.log('file:', file, 'fileList:', fileList)
      this.file = file.raw
    },
    // 移除
    handleRemove (file, fileList) {
      console.log('000:', file, '111:', fileList)
      this.file = ''
    },
    // 批量导入
    async handleSave () {
      try {
        if (!this.file) {
          this.$message.warning(`请导入表格`)
          return
        }
        const formData = new FormData()
        formData.append('file', this.file)
        formData.append('userType', 0)
        const res = await importStudentTemperature(formData)
        if (res && res.code === 0) {
          this.$message.success('导入成功！')
          this.visibleBrachAdd = false
          this.file = ''
          this.onSubmit()
        }
      } catch (e) { }
    },
    // 导入fun
    handleBrachAdd () {
      this.visibleBrachAdd = true
    },
    // 导出
    handleExport () {
      let temp = {}
      Object.assign(temp, this.queryParams, { ids: this.tableSelectIds })
      temp.beginTime = this.measureTime ? this.measureTime[0] : ''
      temp.endTime = this.measureTime ? this.measureTime[1] : ''
      temp.userType = 0
      temp.gradeNo = temp?.gradeNo?.no || null
      exportTemperatureStudent(temp).then(res => {
        if (res.code !== 0) return this.$message.warning('导出失败')
        this.$message.success('导出成功')
      })
    },
    // 批量导入 取消按钮
    handleCancelAdd () {
      this.visibleBrachAdd = false
    },
    // 编辑
    handleEdit (row) {
      this.details = {
        ...row,
        temperatureInfo: (row.temperatureInfo || [{}]).map((item) => {
          return {
            temperature: item.temperature || null,
            measureTime: item.measureTime || null,
            delTemperature: item.temperature || null
          }
        })
      }
      // this.ruleForm.temperature = row.temperature
      // this.ruleForm.measureTime = row.measureTime
      this.dialogEditVisible = true
    },
    // 编辑 confirm
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let temp = {}
          temp.idCard = this.details.idCard
          temp.day = this.details.day
          Object.assign(temp, {
            temperatureInfo: this.details.temperatureInfo.map(item => {
              return {
                temperature: item.temperature,
                measureTime: item.measureTime
              }
            })
          })

          await saveTemperatureStudent({ encryptParam: encrypt(temp) }).then((res) => {
            if (res.code === 0) {
              this.$message.success('编辑成功！')
              this.loadDataList()
              this.dialogEditVisible = false
            }
          })
        }
      })
    },
    // 编辑 cancle
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.dialogEditVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-title {
  display: flex;
  justify-content: flex-end;
  margin-right: 25px;

  .dialog-btn {
    font-size: 18px;
  }
}

.switch-btn {
  width: 50px;
  height: 30px;
  line-height: 30px;
  font-size: 30px;
  text-align: center;
}

.detail-top {
  margin-bottom: 20px;
}

/deep/ .el-input-number__decrease {
  border-radius: 20px 0 0 20px;
}

/deep/ .el-input-number__increase {
  border-radius: 0 20px 20px 0;
}

/deep/ .el-range-editor--small .el-range-separator {
  width: 20px;
}

.titleaa {
  position: relative;
  padding: 12px 0;

  &::after {
    content: "";
    height: 1px;
    background: #dfe6ec;
    position: absolute;
    bottom: 0;
    left: -10px;
    right: -10px;
  }

  &:first-child {
    padding-top: 0;
  }

  &:last-child {
    &::after {
      height: 0;
    }

    padding-bottom: 0;
  }
}
</style>
